# -*- coding: utf-8 -*-

from dataclasses import dataclass
import os, sys, re, codecs, binascii, cgi, cgitb, datetime, pickle
from flask import render_template
from flask import request

class Lodger:
    def __init__(self):
        self.storage = PickleStorage(self)
        
    def ShowForm(self, id):
        return self.storage.GetItem(id).ShowForm()
        
    def ShowLodger(self):
        return render_template('lodger.tpl', items=self.storage.GetItems())
        
    def Add(self):
        item = self.storage.GetItem(int( request.form.get('id', 0) ))
        item.SetFormData(request.form)
        self.storage.Add(item);
        return self.ShowLodger()
            
    def Delete(self, id):
        self.storage.Delete(id)
        return self.ShowLodger()

class PickleStorage:
    def __init__ (self, lodger):
        self.lodger = lodger
        try:
            self.Load()
        except:
            self.items = {}
            self.maxid = 0

    def Load(self):
        with open('lodger.db', 'rb') as f:
            (self.maxid, self.items) = pickle.load(f)
        
    def Store(self):
        with open('lodger.db', 'wb') as f:
            pickle.dump((self.maxid, self.items), f)

    def GetItem(self, id):
        if id <= 0:
            return LodgerItem()
        else:
            return self.items[id]

    def Add(self, item):
        if item.id <= 0:
            self.maxid += 1;
            item.id = self.maxid
            self.items[item.id] = item
            
    def Delete(self, id):
        del self.items[id]
        
    def GetItems(self):
        for(id, item) in self.items.items():
            yield(item)

@dataclass
class LodgerItem:
    id: int = 0
    fio: str = ""
    room: str = ""
    count: str = ""
    time = 0
    child: str = ""
   
    def __post_init__(self):
        self.time = datetime.datetime.now()

    def Show(self):
        return "BootItem Edit"
    
    def SetFormData(self, form):
        self.id = int(form.get('id'))
        self.fio = form.get('fio')
        self.room = form.get('room')
        self.count = form.get('count')
        self.child = form.get('child')
    
    def ShowForm(self):
        return render_template('form.tpl', it=self)

